package com.yykj.order.center.server.service.impl;

import com.yykj.order.center.server.service.MessageService;
import com.yykj.tencent.im.client.feign.TencentImFeignClient;
import com.yykj.tencent.im.client.form.AddGroupMemberForm;
import com.yykj.tencent.im.client.form.DeleteGroupMemberForm;
import com.yykj.tencent.im.client.form.SendSystemMsgRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.transaction.support.TransactionSynchronizationAdapter;
import org.springframework.transaction.support.TransactionSynchronizationManager;

import java.util.List;

@Component
public class MessageServiceImpl implements MessageService {

    @Autowired
    TencentImFeignClient tencentImFeignClient;

    @Value("${im.systemImId}")
    private String systemImid;//系统账号

    @Override
    public void sendMeg(String fromImId, String toImId, String content) {
        TransactionSynchronizationManager.registerSynchronization(
                new TransactionSynchronizationAdapter() {
                    @Override
                    public void afterCommit() {
                        SendSystemMsgRequest sendSystemMsgRequest = new SendSystemMsgRequest();
                        sendSystemMsgRequest.setFromAccount(fromImId);
                        sendSystemMsgRequest.setToAccount(toImId);
                        sendSystemMsgRequest.setMsgBody(content);
                        tencentImFeignClient.sendSystemMsg(sendSystemMsgRequest);
                    }
                }
        );
    }

    @Override
    public void sendSysMeg(String toImId, String content) {
        this.sendMeg(systemImid, toImId, content);
    }

    @Override
    public void memberAdd(String groupId, List<String> memberList) {
        this.tencentImFeignClient.memberAdd(AddGroupMemberForm.builder()
                .groupId(groupId)
                .silence(1)
                .memberList(memberList)
                .build());
    }

    @Override
    public void memberDelete(String groupId, String reason, List<String> memberList) {
        this.tencentImFeignClient.memberDelete(DeleteGroupMemberForm.builder()
                .groupId(groupId)
                .memberToDel_Account(memberList)
                .reason(reason).build());
    }
}